/**
 * @author wanghs
 * @date 2021/8/3
 */
package work.hongsheng9527.exception.myexception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import work.hongsheng9527.exception.common.myenum.CommonEnum;
import work.hongsheng9527.exception.msg.response.BaseResultBody;

import javax.servlet.http.HttpServletRequest;

/**
 * ControllerAdvice表示处理controller层抛出的异常
 * 这个处理器可以处理controller层抛出的异常
 * 然后对抛出来的某个类型的异常做一个统一的处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的业务异常
     * ExceptionHandler(value = BizException.class)
     * 表示对BizException型异常做处理
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    public BaseResultBody bizExceptionHandler(HttpServletRequest req, BizException e) {
        logger.error("发生业务异常！原因是：{}", e.getErrorMsg());
        return BaseResultBody.error(e.getErrorCode(), e.getErrorMsg());
    }

    /**
     * 处理空指针的异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    public BaseResultBody exceptionHandler(HttpServletRequest req, NullPointerException e) {
        logger.error("发生空指针异常！原因是:", e);
        return BaseResultBody.error(CommonEnum.BODY_NOT_MATCH);
    }


    /**
     * 处理其他异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public BaseResultBody exceptionHandler(HttpServletRequest req, Exception e) {
        logger.error("未知异常！原因是:", e);
        return BaseResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR);
    }
}
